package com.dragon.stack;

import com.dragon.array.DynamicArray;

/**
 * @author dragon
 * @version 1.0
 * @description 数组栈
 * @date created in 2018-12-12
 */
public class ArrayStack<E> implements Stack<E> {

    private DynamicArray<E> dynamicArray;

    private static final int DEFAULT_CAPACITY = 10;

    public ArrayStack() {
        this(DEFAULT_CAPACITY);
    }

    public ArrayStack(int capacity) {
        dynamicArray = new DynamicArray<>(capacity);
    }

    /**
     * 弹栈
     *
     * @return
     */
    @Override
    public E pop() {
        if (dynamicArray.size() == 0) {
            throw new IllegalArgumentException("栈为空,弹栈失败");
        }
        return dynamicArray.remove(dynamicArray.size() - 1);
    }

    /**
     * 推入元素到栈里面
     *
     * @param e
     */
    @Override
    public void push(E e) {
        dynamicArray.add(e);
    }

    /**
     * 栈元素个数
     *
     * @return
     */
    @Override
    public int size() {
        return dynamicArray.size();
    }

    /**
     * 查看栈顶元素不弹栈
     *
     * @return
     */
    @Override
    public E peek() {
        return dynamicArray.get(dynamicArray.size() - 1);
    }

    /**
     * 判断是否为空栈
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return dynamicArray.size() == 0;
    }

    /**
     * 重写栈的toString方法
     *
     * @return
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("top[");
        for (int i = dynamicArray.size() - 1; i >= 0; i--) {
            sb.append(dynamicArray.get(i));
            if (i != 0) {
                sb.append(",");
            }
        }
        sb.append("]bottom");
        return sb.toString();
    }

}
